<?php
/**************************************************************************
 *
 *   Copyright 2010 American Public Media Group
 *
 *   This file is part of AIR2.
 *
 *   AIR2 is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   AIR2 is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with AIR2.  If not, see <http://www.gnu.org/licenses/>.
 *
 *************************************************************************/

require_once 'AIR2_CRUD_Controller.php';

/**
 * Source Controller
 *
 * @author plewis
 * @package default
 */
class Source_Controller extends AIR2_CRUD_Controller {

    public $base_model_name = 'Source';
    public $base_view_name  = 'source';
    public $exposed_relations = array(
        'organizations' => 'SrcOrg',
        'annotations'   => 'SrcAnnotation',
        'submissions'   => 'SrcResponseSet',
        'facts'         => 'SrcFact',
        'activities'    => 'SrcActivity',
        'src_vita'      => 'SrcVita',
        'phone'         => 'SrcPhoneNumber',
        'email'         => 'SrcEmail',
        'address'       => 'SrcMailAddress',
        'uri'           => 'SrcUri',
    );
    public $autoload_relations = array();
    public $column_blacklist = array();
    public $column_whitelist = array('sf_fv_id', 'sf_src_fv_id');
    public $taggable = true;


    /**
     * Add custom relations to queries to this controller
     *
     * @param AIR2_Query $q
     * @param boolean $deeply (optional)
     * @return unknown
     */
    protected function _add_query_load_related(&$q, $deeply=true) {
        if (!$this->rel_uri) { // base Source level
            $q->leftJoin('a.SrcEmail e WITH e.sem_primary_flag = true');
            $q->leftJoin('a.SrcPhoneNumber p WITH p.sph_primary_flag = true');
            $q->leftJoin('a.SrcMailAddress m WITH m.smadd_primary_flag = true');
            $q->leftJoin('a.SrcOrg');
        }
        elseif ($this->rel_uri === 'submissions') {
            $q->leftJoin('a.Inquiry i');
            $q->leftJoin('a.SrcResponse r');
            $q->leftJoin('r.Question q');
            $q->leftJoin('a.Source s');
            $q->groupBy('r.sr_srs_id'); // just return 1st src_response
        }
        elseif ($this->rel_uri === 'facts') {
            $q->leftJoin('a.Fact f');
            $q->leftJoin('a.AnalystFV afv');
            $q->leftJoin('a.SourceFV sfv');
            $q->addSelect('f.fact_uuid as fact_uuid');
            $this->extra_field_defs []= array('name' => 'fact_uuid');
        }
        elseif ($this->rel_uri === 'activities') {
            $q->leftJoin('a.ActivityMaster am');
            $q->leftJoin('a.Source');
        }
        elseif ($this->rel_uri === 'annotations') {
            $q->leftJoin('a.CreUser c');
            $q->leftJoin('c.UserOrg uo WITH uo.uo_home_flag = true');
            $q->leftJoin('uo.Organization o');
        }
        elseif ($this->rel_uri === 'organizations') {
            $q->leftJoin('a.Organization o');
            $q->orderBy('org_display_name ASC');

            // flatten some org fields
            $q->addSelect('o.org_display_name as org_display_name');
            $this->extra_field_defs []= array('name' => 'org_display_name');
            $q->addSelect('o.org_uuid as org_uuid');
            $this->extra_field_defs []= array('name' => 'org_uuid');
        }

        return parent::_add_query_load_related($q, $deeply);
    }


    /**
     * Override to add custom update queries
     *
     * @param Doctrine_Record $record (reference) the record object to modify
     * @param associative-array $data   the radix data to update the record with
     */
    protected function _update_record(&$record, $data) {
        if ($this->rel_uri === 'facts') {
            $fact_uuid = isset($data['fact_uuid']) ? $data['fact_uuid'] : null;
            unset($data['fact_uuid']);

            if ($fact_uuid) {
                $fact = Doctrine::getTable('Fact')->findOneBy('fact_uuid', $fact_uuid);
                if (!$fact) $this->crud_error('Invalid Fact specified!');
                $record->Fact = $fact;
            }
        }
        parent::_update_record($record, $data);
    }


    /**
     * Set the page title
     *
     * @param array   $head
     * @return array
     */
    public function get_html_head($head=array()) {
        if ($this->base_uuid) {
            $src = $this->_find_base();
            $name = $src->src_username;
            if ($src->src_first_name && $src->src_last_name) {
                $name = $src->src_first_name.' '.$src->src_last_name;
            }
            $head['title'] = AIR2_SYSTEM_DISP_NAME." - Source: $name";
        }
        return $head;
    }


    /**
     * Custom data and views for html requests
     *
     * @param associative-array $data
     * @param string  $view_name
     * @return string html body
     */
    public function get_html_body($data, $view_name=null) {
        if (!$this->base_uuid) {
            redirect('search/sources');
        }
        elseif ($this->base_uuid && !$this->rel_uri) { // base Source level
            $data = $this->_html_dashboard($data);
        }
        return parent::get_html_body($data, $view_name);
    }


    /**
     * Get data for HTML dashboard
     *
     * @param associative-array $data
     * @return associative-array
     */
    protected function _html_dashboard($data) {
        // submissions
        $q = $this->build_query($this->base_uuid, 'submissions');
        $q->orderBy('srs_date DESC');
        $q->limit(5);
        $submission_data = $this->fetch_data($q, true, true);

        // facts
        $q = $this->build_query($this->base_uuid, 'facts');
        $q->orderBy('sf_cre_dtim DESC');
        $q->limit(20);
        $sf_data = $this->fetch_data($q, true, true);

        // activities
        $q = $this->build_query($this->base_uuid, 'activities');
        $q->orderBy('sact_dtim DESC');
        $q->limit(5);
        $sact_data = $this->fetch_data($q, true, true);

        // stats
        $stats_data = $this->_stats($this->_find_base()->src_id);

        // src_vita
        $q = $this->build_query($this->base_uuid, 'src_vita');
        $sv_data = $this->fetch_data($q, true, true);

        // annotations
        $q = $this->build_query($this->base_uuid, 'annotations');
        $q->orderBy('a.srcan_upd_dtim DESC');
        $q->limit(4);
        $annot_data = $this->fetch_data($q, true, true);

        // tags
        $q = $this->airtag->create_tag_query($this->_find_base());
        $q->orderBy('added_dtim ASC');
        $tag_data = $this->airtag->exec_tag_query($q, true, true);

        // fact list
        $q = AIR2_Query::create()->from('Fact');
        $fl_data = $this->airquery->execute_query($q, array());

        // organizations
        $q = $this->build_query($this->base_uuid, 'organizations');
        $org_data = $this->fetch_data($q, true, true);

        // states
        $conn = AIR2_DBManager::get_connection();
        $states = $conn->fetchAll('select state_code, state_name from state '.
            'order by state_name ASC');
        foreach ($states as $idx => $vals) {
            $states[$idx] = array_values($vals);
        }

        // countries
        $countries = $conn->fetchAll('select cntry_code, cntry_name from '.
            'country order by cntry_disp_seq ASC');
        foreach ($countries as $idx => $vals) {
            $countries[$idx] = array_values($vals);
        }

        return array(
            'base_url'  => $this->uri_for('source').'/'.$this->base_uuid,
            'src'       => $data,
            'sub_srch'  => $this->uri_for('search/responses',
                array('q' => 'src_uuid='.$this->base_uuid)),
            'subm'      => $submission_data,
            'facts'     => $sf_data,
            'act'       => $sact_data,
            'stats'     => $stats_data,
            'src_vita'  => $sv_data,
            'annot'     => $annot_data,
            'tag'       => $tag_data,
            'fl_data'   => $fl_data,
            'org_data'  => $org_data,
            'states'    => $states,
            'countries' => $countries,
        );
    }


    /**
     *
     *
     * @param unknown $source_id
     * @return unknown
     */
    private function _stats($source_id) {
        $conn = AIR2_DBManager::get_connection();
        $sent = 0; //$conn->fetchOne(''); TODO: tie to src_activity log

        /* FIXME - Should only return from the past year but the data
         * does not support this right now. Uncomment the "AND DATE_ADD..."
         * clauses.
         */
        $resp_qty = $conn->fetchOne('SELECT count(srs_id)
        							FROM src_response_set srs
        							WHERE srs_src_id = ?
        							/* AND DATE_ADD(srs.srs_date, INTERVAL 1 YEAR) > CURDATE() */'
            , array($source_id));

        $inq_qty = $conn->fetchOne('SELECT count(distinct i.inq_id)
									FROM src_response_set srs
									, inquiry i
									WHERE srs.srs_src_id = ?
									AND srs.srs_inq_id = i.inq_id
									/* AND DATE_ADD(srs.srs_date, INTERVAL 1 YEAR) > CURDATE() */'
            , array($source_id));

        $stats_data = array(
            'radix' => array(
                'src_id'        => $source_id,
                'ResponseCount' => $resp_qty,
                'ResponseRate'  => ($inq_qty > 0) ? $resp_qty/$inq_qty : 'N/A',
                'InquiryCount'  => $inq_qty,
            ),
            'metaData' => $this->_create_metadata_basic(
                'src_id',
                array(
                    array('name' => 'src_id'),
                    array('name'=>'ResponseCount'),
                    array('name'=>'ResponseRate'),
                    array('name'=>'InquiryCount'),
                )
            ),
        );
        return $stats_data;
    }


}
